using Microsoft.AspNetCore.Authorization;
using Digitalmes.Application.Mes.Traceability.Workstations.Queries;
using Digitalmes.Infrastructure.IO;

namespace Digitalmes.WebApi.Endpoints.Mes.Traceability;

/// <summary>
/// 产品工站数据追溯查询终结点。
/// </summary>
public sealed class WorkstationTraceabilityEndpoint : EndpointGroupBase
{
    public override void Map(WebApplication app)
    {
        app.MapGroup(this, "mes/traceability", "workstation")
            .RequireAuthorization()
            .MapGet(GetProcessStepPagedListAsync, "list-page")
            .MapGet(DownloadAsync, "download")
            .MapGet(DownloadAllAsync, "download-all");
    }

    [EndpointDescription("分页获取产品在指定工位上的过站信息")]
    public async Task<IApiResult> GetProcessStepPagedListAsync(ISender sender, [AsParameters] GetProcessStepListWithPagedQuery query)
    {
        var result = await sender.Send(query);
        return result.ToApiResult();
    }

    [AllowAnonymous]
    [EndpointDescription("根据筛选信息下载指定条目的数据")]
    public async Task<IResult> DownloadAsync(ISender sender, IExcelExport excelExport, [AsParameters] GetDownloadDataQuery query)
    {
        var result = await sender.Send(query);
        var stream = await excelExport.SaveAsStreamAsync(result.Value);

        var value = result.Value.FirstOrDefault();
        var fileName = value is not null
            ? $"{value.WorkstationCode}_{value.Sn}_{DateTime.Now:yyyyMMddHHmmss}"
            : "empty";
        return Results.File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", $"{fileName}.xlsx");
    }

    [AllowAnonymous]
    [EndpointDescription("根据筛选信息下载所有的数据")]
    public async Task<IResult> DownloadAllAsync(ISender sender, IExcelExport excelExport, [AsParameters] GetDownloadAllDataQuery query)
    {
        var result = await sender.Send(query);
        var stream = await excelExport.SaveAsStreamAsync(result.Value);

        var value = result.Value.FirstOrDefault();
        var fileName = value is not null
           ? $"{value.WorkstationCode}_{DateTime.Now:yyyyMMddHHmmss}"
           : "empty";
        return Results.File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", $"{fileName}.xlsx");
    }
}
